package com.artup.controller;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.artup.common.ResponseResult;
import com.artup.service.AuthorityService;
import com.github.botaruibo.xvcode.generator.Generator;
import com.github.botaruibo.xvcode.generator.GifVCGenerator;

/**
 * 权限
 * @author hapday
 * @date 2017年8月31日 @Time 下午7:43:23
 */
@Controller
public class AuthorityController {
	private static final Logger LOGGER = LoggerFactory.getLogger(AuthorityController.class);
	
	@Autowired
	private AuthorityService authorityService;
	
	/**
	 * 转到登陆页面
	 * @return
	 */
	/*@RequestMapping( value = { "toLogin" }, method = { RequestMethod.GET } )
	public String toLogin() {
		return "authority/login";
	}*/

	/**
	 * 登陆
	 * @param username
	 * @param password
	 * @param captcha
	 * @param httpServletRequest
	 * @param httpSession
	 * @return
	 */
	@RequestMapping( value = { "signin" }, method = { RequestMethod.POST } )
	public @ResponseBody ResponseResult signin(String username, String password, String captcha, HttpServletRequest httpServletRequest, HttpSession httpSession) {
		LOGGER.info("username = {}", username);
		
		String clientIP = this.getClientRealIP(httpServletRequest);
		
		ResponseResult responseResult = this.authorityService.signin(username, password, captcha, clientIP, httpSession);
        
		return responseResult;
	}

	/**
	 * 验证码生成器
	 * @param httpSession
	 * @param reponse
	 */
	@RequestMapping( value = { "captchaGenerator" }, method = { RequestMethod.GET } )
	public void captchaGenerator(HttpSession httpSession, HttpServletResponse reponse) {
		Integer height = 40;	// image 高度。  image height. count as pixel
		Integer width = 116;	// image 宽度。 image width. count as pixel
		Integer count = 5;  	// 字符数 validation code length.
		
		Generator generator = new GifVCGenerator(width, height, count);//   gif
		try {
			generator.write2out(reponse.getOutputStream()).close();
		} catch (IOException e) {
			LOGGER.error("验证码生成 - 失败！", e);
		};
		
		String validCode = generator.text();
		System.out.println(validCode);
		LOGGER.debug("sessionID = {}", httpSession.getId());
		
		httpSession.setAttribute(httpSession.getId(), validCode);
	}

	/**
	 * 转到首页
	 * @return
	 */
	/*@RequestMapping( value = { "index" }, method = { RequestMethod.GET } )
	public String toIndex() {
		return "authority/index";
	}*/

	/**
	 * 退出
	 * @return
	 */
	@RequestMapping( value = { "logout" }, method = { RequestMethod.GET } )
	public @ResponseBody ResponseResult logout(String username) {
		LOGGER.info("username = " + username);
		
		ResponseResult responseResult = this.authorityService.logout(username);
		
		return responseResult;
	}
	
	/**
	 * 取得客户端的真实 IP
	 * @param request
	 * @return
	 */
	private String getClientRealIP(HttpServletRequest request){  
        String ipAddress = request.getHeader("x-forwarded-for");  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("WL-Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getRemoteAddr();  
                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                    //根据网卡取本机配置的IP  
                    InetAddress inet=null;  
                    try {  
                        inet = InetAddress.getLocalHost();  
                    } catch (UnknownHostException e) {  
                        e.printStackTrace();  
                    }  
                    ipAddress= inet.getHostAddress();  
                }  
            }  
            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  
            if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
                if(ipAddress.indexOf(",")>0){  
                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
                }  
            }  
            return ipAddress;   
    }
	
	/**
	 * 注册
	 * @param username
	 * @param password
	 * @param captcha
	 * @param httpServletRequest
	 * @param httpSession
	 * @return
	 */
	@RequestMapping( value = { "register" } )
	public @ResponseBody ResponseResult register(String username, String password, String nickname, String captcha, HttpServletRequest httpServletRequest, HttpSession httpSession) {
		LOGGER.info("username = " + username);
		
		ResponseResult responseResult = this.authorityService.register(username, password, nickname, captcha, this.getClientRealIP(httpServletRequest), httpSession);
		
		return responseResult;
	}
}
